package com.liww.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * spring完全加载完成后，测试数据库连接
 * 
 * @author liuzy
 * @since 2015年7月31日
 */
public class DataSourceInitListener implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	private DataSource dataSource;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			Connection connection = null;
			try {
				connection = dataSource.getConnection();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
				System.out.println("数据库连接失败，程序退出!");
				System.exit(0);
			} finally {
				if (connection != null) {
					try {
						connection.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
